<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="培养方案" prop="trainingProgramId">
        <el-select v-model="form.trainingProgramId" placeholder="请选择培养方案" clearable style="width: 150px;">
          <el-option
              v-for="tm in trainingManagementList"
              :key="tm.id"
              :label="tm.name"
              :value="tm.id"
          />
        </el-select>
      </el-form-item>
      <!--年级-->
      <el-form-item label="年级" prop="gradeId">
        <el-select v-model="form.gradeId" placeholder="请选择年级" clearable style="width: 150px;">
          <el-option
              v-for="dict in grade"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程类型" prop="courseCharacter">
        <el-select v-model="queryParams.courseCharacter" placeholder="请选择课程类型" clearable style="width: 150px;">
          <el-option
              v-for="dict in type_of_course"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!--开课学期-->
      <el-form-item label="开课学期" prop="term">
        <el-select v-model="queryParams.semester" placeholder="请选择开课学期" clearable style="width: 150px;">
          <el-option
              v-for="dict in semester"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程" prop="courseId">
        <el-select v-model="queryParams.courseId" placeholder="请选择课程" clearable style="width: 150px;">
          <el-option
              v-for="item in courseList"
              :key="item.id"
              :label="item.courseName"
              :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选课" prop="electiveSystem">
        <el-select v-model="queryParams.electiveSystem" placeholder="请选择是否需要选课" clearable style="width: 150px;">
          <el-option
              v-for="dict in y_n"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="总学时" prop="totalHours" clearable style="width: 200px;">
        <el-input
            v-model="queryParams.totalHours"
            placeholder="请输入总学时"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学分" prop="credits" clearable style="width: 200px;">
        <el-input
            v-model="queryParams.credits"
            placeholder="请输入学分"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="授课方式" prop="teachingMethod">
        <el-select v-model="queryParams.teachingMethod" placeholder="请选择授课方式" clearable style="width: 150px;">
          <el-option
              v-for="dict in teaching_method"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="考试方式" prop="examMethod">
        <el-select v-model="queryParams.examMethod" placeholder="请选择考试方式" clearable style="width: 150px;">
          <el-option
              v-for="dict in method_examination"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否必修" prop="isRequired">
        <el-select v-model="queryParams.isRequired" placeholder="请选择是否必修" clearable style="width: 150px;">
          <el-option
              v-for="dict in compulsory"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['trainingManagement:programPourses:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['trainingManagement:programPourses:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['trainingManagement:programPourses:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['trainingManagement:programPourses:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="programPoursesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="课程名称" align="center">
        <template #default="scope">
          {{ getCourseNameById(scope.row.courseId) }}
        </template>
      </el-table-column>
      <el-table-column label="年级" align="center" prop="grade">
        <template #default="scope">
          <dict-tag :options="grade" :value="scope.row.grade"/>
        </template>
      </el-table-column>
      <el-table-column label="开课学期" align="center" prop="semester">
        <template #default="scope">
          <dict-tag :options="semester" :value="scope.row.semester" />
        </template>
      </el-table-column>
      <!--培养方案名称-->
      <el-table-column label="培养方案名称" align="center">
        <template #default="scope">
          {{ getTrainingManagementName(scope.row.trainingProgramId) }}
        </template>
      </el-table-column>
      <el-table-column label="总学时" align="center" prop="totalHours" />
      <el-table-column label="学分" align="center" prop="credits" />
      <el-table-column label="授课方式" align="center" prop="teachingMethod">
        <template #default="scope">
          <dict-tag :options="teaching_method" :value="scope.row.teachingMethod" />
        </template>
      </el-table-column>
      <el-table-column label="考试方式" align="center" prop="examMethod">
        <template #default="scope">
          <dict-tag :options="method_examination" :value="scope.row.examMethod" />
        </template>
      </el-table-column>
      <el-table-column label="课程性质" align="center" prop="courseCharacter">
        <template #default="scope">
          <dict-tag :options="characteristics_of_the_course" :value="scope.row.courseCharacter" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['trainingManagement:programPourses:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['trainingManagement:programPourses:remove']">删除</el-button>
          <el-button link type="primary" icon="RefreshRight" @click="handleChangeStatus(scope.row)" v-hasPermi="['trainingManagement:programPourses:edit']">
            修改状态
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改培养计划课程明细对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="programPoursesRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="培养计划ID" prop="trainingProgramId">
          <el-select v-model="form.trainingProgramId" placeholder="请选择培养方案" required>
            <el-option
                v-for="tm in trainingManagementList"
                :key="tm.id"
                :label="tm.name"
                :value="tm.id"
            />
          </el-select>
        </el-form-item>
        <!--年级-->
        <el-form-item label="年级" prop="grade">
          <el-select v-model="form.grade" placeholder="请选择年级">
            <el-option
                v-for="dict in grade"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程类型" prop="courseCharacter">
          <el-select v-model="form.courseCharacter" placeholder="请选择课程类型">
            <el-option
                v-for="dict in type_of_course"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程" prop="courseId">
          <el-select v-model="form.courseId" placeholder="请选择课程ID" clearable>
            <el-option
                v-for="item in courseList"
                :key="item.id"
                :label="item.courseName"
                :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!--开课学期-->
        <el-form-item label="开课学期" prop="semester">
          <el-select v-model="form.semester" placeholder="请选择开课学期" clearable>
            <el-option
                v-for="dict in semester"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否需要选课" prop="electiveSystem">
          <el-select v-model="form.electiveSystem" placeholder="请选择是否需要选课" clearable>
            <el-option
                v-for="dict in y_n"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="总学时" prop="totalHours">
          <el-input v-model="form.totalHours" placeholder="请输入总学时" />
        </el-form-item>
        <el-form-item label="学分" prop="credits">
          <el-input v-model="form.credits" placeholder="请输入学分" />
        </el-form-item>
        <el-form-item label="授课方式" prop="teachingMethod">
          <el-select v-model="form.teachingMethod" placeholder="请选择授课方式">
            <el-option
                v-for="dict in teaching_method"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="考试方式" prop="examMethod">
          <el-select v-model="form.examMethod" placeholder="请选择考试方式">
            <el-option
                v-for="dict in method_examination"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否必修" prop="isRequired">
          <el-select v-model="form.isRequired" placeholder="请选择是否必修">
            <el-option
                v-for="dict in characteristics_of_the_course"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="记录创建时间" prop="createdAt">
          <el-date-picker clearable
                          v-model="form.createdAt"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择记录创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="记录更新时间" prop="updatedAt">
          <el-date-picker clearable
                          v-model="form.updatedAt"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择记录更新时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
        title="确认修改状态"
        v-model="showStatusDialog"
        width="30%"
        :before-close="handleCloseStatusDialog"
    >
      <div>需要将培养方案对应的课程加入排课任务吗？</div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showStatusDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmChangeStatus">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ProgramPourses">
import {
  listProgramPourses,
  getProgramPourses,
  delProgramPourses,
  addProgramPourses,
  updateProgramPourses,
  updateStatusById
} from "@/api/trainingManagement/programPourses";
import {listCourse} from "@/api/course/course";
import {loadAllParams} from "@/api/page";
import {listTrainingManagement} from "@/api/trainingManagement/trainingManagement";
import {useRouter} from 'vue-router';
const router = useRouter();
import DictTag from "@/components/DictTag/index.vue";

const {proxy} = getCurrentInstance();
const {
  type_of_course,
  y_n,
  method_examination,
  teaching_method,
  compulsory,
  semester,
  grade,
  characteristics_of_the_course,
  teaching_task_status
} = proxy.useDict('type_of_course', 'y_n', 'method_examination', 'teaching_method', 'compulsory', 'semester', "grade",'characteristics_of_the_course', 'teaching_task_status');

const programPoursesList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
// 添加状态对话框相关变量
const showStatusDialog = ref(false);
const currentRow = ref(null);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10000,
    trainingProgramId: null,
    courseCharacter: null,
    courseId: null,
    electiveSystem: null,
    totalHours: null,
    credits: null,
    teachingMethod: null,
    examMethod: null,
    isRequired: null,
    grade: null,
    createdAt: null,
    updatedAt: null
  },
  rules: {
    trainingProgramId: [
      {required: true, message: "培养计划ID不能为空", trigger: "blur"}
    ],
    courseId: [
      {required: true, message: "课程ID不能为空", trigger: "blur"}
    ],
  }
});
// 打开状态修改对话框
function handleChangeStatus(row) {
  currentRow.value = row;
  showStatusDialog.value = true;
}

// 关闭状态对话框
function handleCloseStatusDialog() {
  showStatusDialog.value = false;
  currentRow.value = null;
}

// 确认修改状态
function confirmChangeStatus() {
  if (currentRow.value && currentRow.value.id) {
    // 调用接口，传入id和状态2
    updateStatusById(currentRow.value.id, 2).then(response => {
      if (response > 0) {
        proxy.$modal.msgSuccess("状态修改成功");
        showStatusDialog.value = false;
        getList(); // 刷新列表
      } else {
        proxy.$modal.msgError("状态修改失败");
      }
    }).catch(error => {
      console.error("修改状态失败:", error);
      proxy.$modal.msgError("修改状态失败，请重试");
    });
  }
}

const {queryParams, form, rules} = toRefs(data);
const courseNameMap = computed(() => {
  const map = new Map();
  courseList.value.forEach(course => {
    map.set(course.id, course.courseName);
  });
  return map;
});
const trainingNameMap = computed(() => {
  const map = new Map();
  trainingManagementList.value.forEach(tm => {
    map.set(tm.id, tm.name);
  });
  return map;
});
const getCourseNameById = (courseId) => {
  return courseNameMap.value.get(courseId) || '未知课程';
};
// 获取状态显示文本
const getStatusText = (status) => {
  // 空值处理（保持不变）
  if (status === undefined || status === null || status === '' || status === 'null') {
    return '待加入排课任务';
  }

  // 关键修复：将状态值转为字符串，与字典的string类型value匹配
  const statusStr = String(status);
  // 直接比较字符串
  const dictItem = teaching_task_status.value.find(item => item.value === statusStr);

  // 调试信息：查看匹配过程
  console.log(`状态值: ${status}（原始类型: ${typeof status}），转换后: ${statusStr}，匹配结果:`, dictItem);

  return dictItem ? dictItem.label : `未知状态(${status})`;
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  // 空值处理
  if (status === undefined || status === null || status === '' || status === 'null') {
    return 'warning';
  }

  // 转为字符串匹配
  const statusStr = String(status);
  // 可根据实际字典值设置不同样式（示例）
  switch (statusStr) {
    case "1":
      return "info"; // 待加入排课任务
    case "2":
      return "success"; // 已加入排课任务
    case "3":
      return "primary"; // 完成排课任务
    default:
      return "danger"; // 未知状态
  }
};
/** 查询培养计划课程明细列表 */
async function getList() {
  loading.value = true;
  try {
    const response = await listProgramPourses(queryParams.value);
    let rows = response.rows;

    // 处理状态值：转换为数字类型
    rows = rows.map(item => ({
      ...item,
      //statusNum: Number(item.status) || 0
    }));

    programPoursesList.value = rows;
    total.value = response.total;
  } catch (error) {
    console.error("数据加载失败:", error);
    proxy.$modal.msgError("数据加载失败，请检查网络连接");
  } finally {
    loading.value = false;
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    trainingProgramId: null,
    courseCharacter: null,
    courseId: null,
    electiveSystem: null,
    totalHours: null,
    credits: null,
    teachingMethod: null,
    examMethod: null,
    isRequired: null,
    semester: null,
    createdAt: null,
    updatedAt: null
  };
  proxy.resetForm("programPoursesRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加培养计划课程明细";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getProgramPourses(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改培养计划课程明细";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["programPoursesRef"].validate(valid => {
    if (valid) {
      console.log("提交的数据", form.value);
      if (form.value.id != null) {
        updateProgramPourses(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addProgramPourses(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除培养计划课程明细编号为"' + _ids + '"的数据项？').then(function () {
    return delProgramPourses(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('trainingManagement/programPourses/export', {
    ...queryParams.value
  }, `programPourses_${new Date().getTime()}.xlsx`)
}

/**查询课程列表 */
const courseList = ref([]);

function getCourseList() {
  return new Promise((resolve) => {
    if (courseList.value.length > 0) {
      resolve();
      return;
    }

    listCourse(loadAllParams).then(response => {
      courseList.value = response.rows;
      resolve();
    });
  });
}

//查询培养方案列表
const trainingManagementList = ref([]);
const getTrainingManagementList = async () => {
  if (trainingManagementList.value.length > 0) return;

  try {
    const response = await listTrainingManagement({});
    trainingManagementList.value = response.rows;
  } catch (error) {
    console.error('获取培养方案列表失败:', error);
    proxy.$modal.msgError('培养方案加载失败');
  }
};

const initData = async () => {
  loading.value = true;
  try {
    // 并行加载必要数据
    await Promise.all([
      getCourseList(),
      getTrainingManagementList(),
      getList()
    ]);
  } catch (error) {
    console.error("数据加载失败:", error);
    proxy.$modal.msgError("数据加载失败");
  } finally {
    loading.value = false;
  }
};

//根据培养方案 ID 获取培养方案名称
function getTrainingManagementName(trainingProgramId) {
  const trainingManagement = trainingManagementList.value.find(tm => tm.id === trainingProgramId);
  return trainingManagement ? trainingManagement.name : '未知培养方案';
}

// 根据课程 ID 获取课程名称
function getCourseName(courseId) {
  const course = courseList.value.find(c => c.id === courseId);
  return course ? course.courseName : '未知课程';
}

onMounted(() => {
  getCourseList();
  getTrainingManagementList();
  getList();
  initData();
  console.log("teaching_task_status字典完整数据:", teaching_task_status.value);
  // 检查是否有value=2的项
  const hasStatus2 = teaching_task_status.value.some(item => Number(item.value) === 2);
  console.log("字典中是否包含状态2:", hasStatus2); // 应为true
});
</script>
<style scoped>
/* 状态标签样式 */
.el-tag {
  font-size: 12px;
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
}

.el-tag--success {
  background-color: #f0f9eb;
  border-color: #e1f3d8;
  color: #67c23a;
}

.el-tag--info {
  background-color: #f4f4f5;
  border-color: #e9e9eb;
  color: #909399;
}

/* 优化按钮显示 */
.el-button {
  transition: all 0.3s ease;
}

.el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 表格行悬停效果 */
.el-table__body tr:hover>td {
  background-color: #f5f7fa !important;
}

/* 搜索区域样式优化 */
.app-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-form-item {
  margin-bottom: 16px;
}

/* 操作按钮区域 */
.mb8 {
  margin-bottom: 16px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .el-form-item {
    width: 100%;
  }

  .el-select, .el-input {
    width: 100% !important;
  }
}
</style>
